//
//  AuthCore.m
//  HHNMobileCore
//
//  Created by huhmf on 15/7/23.
//  Copyright (c) 2015年 huhmf. All rights reserved.
//

#import "AuthCore.h"
#import "requestLoginApi.h"
#import "CommonFileUtils.h"
#import "CoreManager.h"
#import <MJExtension.h>
#import "SSKeychain.h"
#import "SSKeychainQuery.h"
#import "AccountInfo.h"
#import "RequestAppInitApi.h"
#import "RequestAppheartApi.h"
#import "RequestLogoutApi.h"
#import "RequestPartyLogin.h"
//加密的service
static NSString *const AllLoginAccountKeyChainService_qsh = @"AllEncryptedLoginAccountKeyChainService_qsh";

@implementation AuthCore

#pragma mark - 实现协议IAuthClient

-(void)requestLoginWithUserName:(NSString *)userName password:(NSString *)password code:(NSString *)code SuccBlock:(void (^)())succBlock failBLock:(void (^)(NSString *))failBlock
{
    requestLoginApi *api=[[requestLoginApi alloc]initWithUsername:userName password:password code:code];
    api.ignoreCache=YES;
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {

        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseString.mj_JSONData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        if(err) {
            HHLog(@"json解析失败：%@",err);
            return;
        }
//        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
//            HHLog(@"%@, %@",key,obj);
//        }];
        
         NSString *code=[dict valueForKey:@"result"];
        int codeValue = [code intValue];
         NSString *msg=[dict valueForKey:@"msg"];
        if (codeValue != 0) {
            HHLog(@"登录失败：%@",msg);
            [self clearStorage];
            failBlock(msg);
            return;
        }
        
        if([[dict valueForKey:@"data"] isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *dict_data=[dict valueForKey:@"data"];
            if( [dict_data  isKindOfClass:[NSDictionary class]])
            {
//                NSDictionary *dict_user=[dict_data valueForKey:@"user"];
                
                [AccountInfo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                    return @{
                             @"userId" : @"userId",
                             @"birthday" :@"birthday",
                             @"avatar":@"avatar",
                             @"mobilePhone":@"cellPhone",
                             @"userName":@"nickName",
                             @"realName":@"userName",
                             @"sex":@"sex",
                             @"encodeMobile":@"encodeMobile"
                             
                             };
                }];
                
                AccountInfo *userInfo=[AccountInfo mj_objectWithKeyValues:dict_data];
                //把归档把结果缓存起来
        
                [CommonFileUtils writeObject:userInfo toDocumentPath:@"userInfo"];
                
                [CommonFileUtils writeObject:userName toUserDefaultWithKey:@"userName"];
                
                //使用apple 的钥匙串进行管理密码
                [SSKeychain setPassword:password forService:AllLoginAccountKeyChainService_qsh account:userName];
                
                //NSString *encrytedPassword2=[SSKeychain passwordForService:AllLoginAccountKeyChainService_qsh account:userName];

                
                NotifyCoreClient(IAuthClient, @selector(onLoginSucceed:),onLoginSucceed:userInfo.userId);
                
                succBlock();
                
                
            }
            else{
                HHLog(@"返回json数据error");
                [self clearStorage];
                failBlock(@"服务器错误");
                return;
            }
        }else{
            HHLog(@"返回json数据error");
            [self clearStorage];
            failBlock(@"服务器错误");
            return;
        }

    } failure:^(YTKBaseRequest *request) {
        HHLog(@"%@",request.requestTask.error.localizedDescription);
        [self clearStorage];
        failBlock(request.requestTask.error.localizedDescription);

    }];

}

-(void) requestLogoutWithAppVersion:(NSString *) appVersion andPlatform:(NSString *) platform andType:(NSString *)type SuccBlock:(void(^)())succBlock failBlock:(void(^)(NSString *msg)) failBlock {
    
    RequestLogoutApi *api = [[RequestLogoutApi alloc] initRequestLogoutWithAppVerson:appVersion andPlatForm:platform andType:type];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request){
        
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseString.mj_JSONData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        
        int codeVlue=[((NSNumber *)[dict valueForKey:@"code"]) intValue];
        NSString *msg = [dict valueForKey:@"msg"];
        if (codeVlue!=0) {
            
            failBlock(msg);return;
        }
        [self clearStorage];
        succBlock();
    }failure:^(YTKBaseRequest *request){
        HHLog(@"%@",request.requestTask.error.localizedDescription);
        [self clearStorage];
        failBlock(request.requestTask.error.localizedDescription);
        
    }];
    
}

- (void) appInitWithSuccessBlock:(void(^)()) successBlock andFailBlock:(void(^)(NSString *msg)) failBlock {
    
    
    RequestAppInitApi *api = [[RequestAppInitApi alloc] init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request){
        
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseString.mj_JSONData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        
        int codeVlue=[((NSNumber *)[dict valueForKey:@"code"]) intValue];
        NSString *msg = [dict valueForKey:@"msg"];
        if (codeVlue!=0) {
            
            failBlock(msg);return;
        }
        
        successBlock();
    }failure:^(YTKBaseRequest * request) {
        
        HHLog(@"%@",request.requestTask.error.localizedDescription);
        failBlock(request.requestTask.error.localizedDescription);
        
    }];
}


-(void) appheartBeatSuccessBlock:(void(^)(BOOL isLogin)) successBlock andFailBlock:(void(^)(NSString *msg)) failBlock {
    
    
    RequestAppheartApi *api = [[RequestAppheartApi alloc] init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request){
        
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseString.mj_JSONData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        
        int codeVlue=[((NSNumber *)[dict valueForKey:@"code"]) intValue];
        BOOL isLogin = [[dict valueForKey:@"isLogin"] boolValue];
        NSString *msg = [dict valueForKey:@"msg"];
        if (codeVlue!=0) {
            
            failBlock(msg);return;
        }
        
        successBlock(isLogin);
    }failure:^(YTKBaseRequest * request) {
        
        HHLog(@"%@",request.requestTask.error.localizedDescription);
        failBlock(request.requestTask.error.localizedDescription);
        
    }];
}

-(void) requestPartyLoginWith:(NSString *) openId andType:(NSString*) type andSuccessBlock:(void(^)(BOOL isLogin)) successBlock andFailBlock:(void(^)(NSString *msg)) failBlock {
    
    
    RequestPartyLogin *api = [[RequestPartyLogin alloc] initWithOpenId:openId andType:type];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request){
        
        NSError *err;
        HHLog(@"response  = %@",request.responseString);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseString.mj_JSONData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        int codeVlue=[((NSNumber *)[dict valueForKey:@"code"]) intValue];
        BOOL isLogin = [[dict valueForKey:@"isLogin"] boolValue];
        NSString *msg = [dict valueForKey:@"msg"];
        if (codeVlue!=0) {
            
            failBlock(msg);return;
        }else {
            
            if([[dict valueForKey:@"data"] isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dict_data=[dict valueForKey:@"data"];
                if( [dict_data  isKindOfClass:[NSDictionary class]])
                {
                    //                NSDictionary *dict_user=[dict_data valueForKey:@"user"];
                    
                    [AccountInfo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                        return @{
                                 @"userId" : @"userId",
                                 @"birthday" :@"birthday",
                                 @"avatar":@"avatar",
                                 @"mobilePhone":@"cellPhone",
                                 @"userName":@"nickName",
                                 @"realName":@"userName",
                                 @"sex":@"sex",
                                 @"encodeMobile":@"encodeMobile"
                                 
                                 };
                    }];
                    
                    AccountInfo *userInfo=[AccountInfo mj_objectWithKeyValues:dict_data];
                    //把归档把结果缓存起来
                    
                    [CommonFileUtils writeObject:userInfo toDocumentPath:@"userInfo"];
                    [CommonFileUtils writeObject:userInfo.userName toUserDefaultWithKey:@"userName"];
                    sleep(1);
                    //NSString *encrytedPassword2=[SSKeychain passwordForService:AllLoginAccountKeyChainService_qsh account:userName];
                    
                    successBlock(true);
                    return;
                    
                }
                else{
                    HHLog(@"返回json数据error");
                    [self clearStorage];
                    failBlock(@"服务器错误");
                    return;
                }
            }else{
                HHLog(@"返回json数据error");
                [self clearStorage];
                failBlock(@"服务器错误");
                return;
            }
       
        }
        
    }failure:^(YTKBaseRequest * request) {
        
        HHLog(@"%@",request.requestTask.error.localizedDescription);
        failBlock(request.requestTask.error.localizedDescription);
        
    }];
}
/**
 *  清除缓存
 */
-(void)clearStorage
{
    //退出登录，清空cookie,用户名...
    [CommonFileUtils deleteObjectFromUserDefaultWithKey:@"userName"];
    [CommonFileUtils deleteFileFromDocumentPath:@"userInfo"];
    //清空Cookie
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *_tmpArray = [NSArray arrayWithArray:[cookieStorage cookies]];
    for (id obj in _tmpArray) {
        [cookieStorage deleteCookie:obj];
    }
}

#pragma mark - 实现协议IAuthQuery
-(AccountInfo *)getAccountInfo
{
    AccountInfo *userInfo =[CommonFileUtils readObjectFromDocumentPath:@"userInfo"];
    return userInfo;
}

-(NSString *)getUserName
{
    return [CommonFileUtils readObjectFromUserDefaultWithKey:@"userName"];
    
}


-(NSString *) getPassword:(NSString *) userName {
    
    NSString *passWord =   [SSKeychain passwordForService:AllLoginAccountKeyChainService_qsh account:userName];
    return passWord;
}


-(NSString *)getUserId
{
    AccountInfo *userInfo =[CommonFileUtils readObjectFromDocumentPath:@"userInfo"];
    NSString *userId=@"";
    if (userInfo!=nil) {
        userId=[NSNumber numberWithLongLong:userInfo.userId].stringValue;
    }
    return userId;
}

-(NSString *) getEncodeMobile{
    AccountInfo *userInfo =[CommonFileUtils readObjectFromDocumentPath:@"userInfo"];
    NSString *encodeMobile=@"";
    if (encodeMobile!=nil) {
        encodeMobile=userInfo.encodeMobile;
    }
    return encodeMobile;
    
}
@end
